package com.xt.purchasingsystem.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xt.purchasingsystem.annotation.PurchaseCache;
import com.xt.purchasingsystem.annotation.PurchaseClearCache;
import com.xt.purchasingsystem.dto.SysUsersDto;
import com.xt.purchasingsystem.model.SysUsers;
import com.xt.purchasingsystem.service.SysUsersService;
import com.xt.purchasingsystem.utils.FileUtil;
import com.xt.purchasingsystem.utils.IdWorker;
import com.xt.purchasingsystem.utils.Result;
import com.xt.purchasingsystem.utils.ResultFactory;
import io.swagger.annotations.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.UUID;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author yhp
 * @since 2020-05-18
 */
@RestController
@RequestMapping("/user")
@Api(description = "用户管理API")
public class SysUsersController {
    @Autowired
    private SysUsersService sysUsersService;
    @Autowired
    private IdWorker idWorker;

    @GetMapping("/authentication")
    public Result authentication() {
        Subject subject = SecurityUtils.getSubject();

        //3.解析token 如果正常放行


        if (subject.isAuthenticated()) {
            return ResultFactory.buildSuccessResult("用户已登录");
        } else {
            return ResultFactory.buildFailResult("用户没有登录");
        }

    }


    /**
     * 多条件分页查询用户接口
     *
     * @param sysUsersDto
     * @return
     */
    @ApiOperation(value = "多条件分页查询用户", notes = "用户列表")
    @PurchaseCache(prefix = "user:users:dto", timeout = 7200, random = 1000)
    @PostMapping("/querySysUsersBySysUsersDto")
    public Result querySysUsersBySysUsersDto(@RequestBody @ApiParam(name = "sysUsersDto", value = "用户Dto对象", required = true) SysUsersDto sysUsersDto) {
        return sysUsersService.querySysUsersBySysUsersDto(sysUsersDto);

    }

    /**
     * 根据用户编号修改用户状态的接口
     *
     * @param id
     * @param status
     * @return
     */
    @ApiOperation(value = "根据用户编号修改用户状态的接口", notes = "根据用户编号修改用户状态的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "id", value = "用户ID", required = true, dataType = "Long"),
            @ApiImplicitParam(paramType = "path", name = "status", value = "状态码,1为可用,0为不可用", required = true, dataType = "Integer"),
    })
    @PurchaseClearCache(prefix = "user")
    @PutMapping("/updateUserStatusById/{id}/{status}")
    public Result updateUserStatusById(@PathVariable("id") String id,
                                       @PathVariable("status") Integer status) {
        return sysUsersService.updateUserStatusById(id, status);
    }

    /**
     * 添加用户的接口
     *
     * @param sysUsers
     * @return
     */
    @ApiOperation(value = "添加用户的接口", notes = "添加用户的接口")
    @PostMapping("/saveUser")
    @PurchaseClearCache(prefix = "user")
    public Result saveUser(@RequestBody @ApiParam(name = "sysUsers", value = "用户对象", required = true) SysUsers sysUsers) {
        sysUsers.setId(String.valueOf(idWorker.nextId()));

        return sysUsersService.saveUser(sysUsers);

    }

    /**
     * 修改用户的接口
     *
     * @param sysUsers
     * @param request
     * @return
     */
    @ApiOperation(value = "修改用户的接口", notes = "修改用户的接口")
    @PostMapping("/updateUser")
    @PurchaseClearCache(prefix = "user")
    public Result updateUser(@RequestBody @ApiParam(name = "sysUsers", value = "用户对象", required = true) SysUsers sysUsers, HttpServletRequest request) {
        SysUsers user = sysUsersService.getById(sysUsers.getId());
        //判断要修改的用户是否要上传图片
        if (sysUsers.getPhotoPath().length() <= 0) {
            //不需要上传图片
            //查询此用户有没有图片
            if (user.getPhotoPath().length() > 0) {
                //原来有图片 要把图片删除
                FileUtil.deleteFile(user.getPhotoPath());
            }
            boolean flag = sysUsersService.saveOrUpdate(sysUsers);
            if (flag) {
                return ResultFactory.buildSuccessResult("修改成功");
            } else {
                return ResultFactory.buildFailResult("修改失败");
            }

        } else {
            if (!sysUsers.getPhotoPath().equals(user.getPhotoPath())) {
                FileUtil.deleteFile(user.getPhotoPath());
                sysUsers.setPhotoPath("");
            }
            boolean flag = sysUsersService.saveOrUpdate(sysUsers);
            if (flag) {
                return ResultFactory.buildSuccessResult("修改成功");
            } else {
                return ResultFactory.buildFailResult("修改失败");
            }
        }
    }

    /**
     * 上传用户头像的接口
     *
     * @param photo
     * @param request
     * @return
     */

    @ApiOperation(value = "上传用户头像的接口")
    @ApiImplicitParam(paramType = "path", name = "type", value = "类型", required = true, dataType = "String")
    @PostMapping("/uploadUserPhoto/{type}")
    @PurchaseClearCache(prefix = "user")
    public String uploadUserPhoto(@RequestParam("photo") @ApiParam(name = "photo", value = "照片对象", required = true) MultipartFile photo,
                                  HttpServletRequest request, @PathVariable("type") String type) {
        if (type.equals("add")) {
            //添加用户时上传头像
            String photopath = request.getParameter("photoPath");
            if (photopath.length() > 0) {
                boolean flag =
                        FileUtil.deleteFile(photopath);
            }
            String originalFilename = photo.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf('.'));
            System.out.println(suffix);
            String abpath = "";
            try {
                abpath = "/images/user/" + UUID.randomUUID().toString().replace("-", "") + suffix;
                System.out.println(abpath);
                photo.transferTo(new File("D://ProjectPhoto//purchasingsystem//" + abpath));

            } catch (Exception e) {
                return "上传头像失败";
            }
            String host = null;
            try {
                host = InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }

//            request.getServerPort() +
//                    //+ ":" + request.getServerPort() //端口 https443端口无需添加
//                    +fileLocation + filename;
            String imgUrl = "http://" + host + ":" + request.getServerPort() + abpath;
            return imgUrl;
        } else {
            //修改用户时上传头像
            String id = request.getParameter("id");
            SysUsers user = sysUsersService.getById(id);
            if (user.getPhotoPath() != null && user.getPhotoPath() != "" && user.getPhotoPath().length() > 0) {
                //原来有图片 要把图片删除
                FileUtil.deleteFile(user.getPhotoPath());
            }
            String photopath = request.getParameter("photoPath");
            if (photopath.length() > 0) {
                boolean flag =
                        FileUtil.deleteFile(photopath);
            }
            String originalFilename = photo.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf('.'));
            String abpath = "";
            try {
                abpath = "/images/user/" + UUID.randomUUID().toString().replace("-", "") + suffix;

                photo.transferTo(new File("D://ProjectPhoto//purchasingsystem//" + abpath));

            } catch (Exception e) {
                return "上传头像失败";
            }
            String host = null;
            try {
                host = InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            String imgUrl = "http://" + host + ":" + request.getServerPort() + abpath;
            user.setPhotoPath(imgUrl);
            sysUsersService.updateById(user);
            return imgUrl;

        }

    }

    /**
     * 根据用户编号删除用户的接口
     *
     * @return
     */
    @ApiOperation(value = "根据用户编号删除用户的接口", notes = "根据用户编号删除用户的接口")
    @DeleteMapping("/deleteUserById")
    @PurchaseClearCache(prefix ={"user","menu:menusBy"})
    public Result deleteUserById(@RequestBody @ApiParam(name = "sysUsersDto", value = "用户Dto对象", required = true) SysUsersDto sysUsersDto) {
        Collection<SysUsers> sysUsers = sysUsersService.listByIds(sysUsersDto.getUserIds());
        for (SysUsers sysUser : sysUsers) {
            FileUtil.deleteFile(sysUser.getPhotoPath());
        }
        boolean flag = sysUsersService.removeByIds(sysUsersDto.getUserIds());
        if (flag){
            return ResultFactory.buildSuccessResult("删除成功");
        }else {
            return ResultFactory.buildFailResult("删除失败");
        }

    }

    /**
     * 根据用户名查询用户的接口 (用于注册用户时检查用户名是否已被注册)
     *
     * @param loginId
     * @return
     */
    @ApiOperation(value = "根据用户名查询用户的接口", notes = "根据用户名查询用户的接口")
    @ApiImplicitParam(paramType = "path", name = "loginId", value = "用户名", required = true, dataType = "String")
    @GetMapping("/checkLoginId/{loginId}")
    @PurchaseCache(prefix = "user:loginId:", timeout = 7200, random = 1000)
    public Result checkLoginId(@PathVariable("loginId") String loginId) {
        SysUsers sysUsers = sysUsersService.getOne(new QueryWrapper<SysUsers>().eq("login_id", loginId));
        if (sysUsers != null) {
            return ResultFactory.buildSuccessResult("查询成功");
        } else {
            return ResultFactory.buildFailResult("查询失败");
        }
    }

    /**
     * 给用户授权角色的接口
     *
     * @param sysUsersDto
     * @return
     */
    @ApiOperation(value = "给用户授权角色的接口", notes = "给用户授权角色的接口")
    @PutMapping("/authorizationRoleByUser")
    @PurchaseClearCache(prefix = "user")
    public Result authorizationRoleByUser(@RequestBody @ApiParam(name = "sysUsersDto", value = "用户Dto对象", required = true) SysUsersDto sysUsersDto) {
        return sysUsersService.authorizationRoleByUser(sysUsersDto.getSysUsers().getId(), sysUsersDto.getRoles());
    }

    /**
     * 用户登录的接口
     *
     * @param sysUsers
     * @return
     */
    @ApiOperation(value = "用户登录的接口", notes = "用户登录的接口")
    @PostMapping("/login")
    @PurchaseCache(prefix = "user:login:", timeout = 7200, random = 1000)
    public Result login(@RequestBody @ApiParam(name = "sysUsers", value = "用户对象", required = true) SysUsers sysUsers) {

        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(sysUsers.getLoginId(),
                sysUsers.getPassword());
        try {
            subject.login(usernamePasswordToken);
            SysUsers s = new SysUsers();
            SysUsers user = sysUsersService.getOne(new QueryWrapper<SysUsers>().eq("login_id", sysUsers.getLoginId()));
            s.setLoginId(user.getLoginId());
            s.setPhotoPath(user.getPhotoPath());
            s.setId(user.getId());
            if (user.getStatus().intValue() != 1) {
                subject.logout();
                return ResultFactory.buildFailResult("此账号已被禁用");
            }
            return ResultFactory.buildSuccessResult("登录成功", s);

        } catch (AuthenticationException e) {
            return ResultFactory.buildFailResult("账号或密码错误");
        }

    }

    /**
     * 根据用户名获取此用户名所有的菜单的接口
     *
     * @param loginId 用户名
     * @return
     */

    @ApiOperation(value = "根据用户名获取此用户名所有的菜单的接口", notes = "根据用户名获取此用户名所有的菜单的接口")
    @ApiImplicitParam(paramType = "path", name = "loginId", value = "用户名", required = true, dataType = "String")
    @PurchaseCache(prefix = "menu:menusByUser:", timeout = 7200, random = 1000)
    @GetMapping("/getMenusByUser/{loginId}")
    public Result getMenusByUser(@PathVariable("loginId") String loginId) {
        return sysUsersService.queryMenuByUser(loginId);
    }

    /**
     * 根据用户编号和父级菜单编号获取此用户此菜单下的所有状态能用(status==1)的子菜单
     *
     * @param userId   用户编号
     * @param parentId 父级菜单编号
     * @return
     */
    @ApiOperation(value = "根据用户编号和父级菜单编号获取此用户此菜单下的所有状态能用(status==1)的子菜单", notes = "根据用户编号和父级菜单编号获取此用户此菜单下的所有状态能用(status==1)的子菜单")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "userId", value = "用户ID", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "path", name = "parentId", value = "菜单父ID", required = true, dataType = "String")
    })
    @PurchaseCache(prefix = "menu:menusByParentMenu:", timeout = 7200, random = 1000)
    @GetMapping("/getMenusByParentMenu/{userId}/{parentId}")
    public Result getMenusByParentMenu(@PathVariable("userId") String userId,
                                       @PathVariable("parentId") String parentId) {
        return sysUsersService.queryMenuByUserAndParentMenu(userId, parentId);
    }
}

